#include <stdio.h>
#include <getch.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "login.h"
#include "tools.h"
#include "initProgram.h"
#include "saveFile.h"

void anykey_continue(void)
{
	puts("任意键继续...");
	stdin->_IO_read_ptr = stdin->_IO_read_end;
	getch();
}


void show_msg(const char* msg,double sec)
{
	printf("%s",msg);
	fflush(stdout);
	usleep(sec*1000000);
}

void logout(int identity)
{
	int ret = saveFile(identity);
	ret == 0 && printf("操作保存成功！\n");
	ret == -1 && printf("操作保存失败，请重试或联系1512377891@qq.com\n");
	anykey_continue();
	login();
}

void lockAccount(int identity, int id)
{
	if(1 == identity)
	{
		student[id-1001].flag = -1;
	}
	if(2 == identity)
	{
		teacher[id-101].flag = -1;
	}
}
Student searchStu(int account, char* password)
{
	Student stu = {};
	for(int i = 0; i < 1000; i++)
	{
		if(account == student[i].id)
		{
			if(0 == strcmp(password, student[i].password))
			{
				strcpy(stu.name, student[i].name);
				strcpy(stu.password, student[i].password);
				stu.chnScore = student[i].chnScore;
				stu.mathScore = student[i].mathScore;
				stu.engScore = student[i].engScore;
				stu.id = student[i].id;
				stu.sex = student[i].sex;
				stu.flag = student[i].flag;
				return stu;
			}
			else
			{
				stu.id = account;
				stu.flag = student[i].flag;
			}
			break;
		}
	}
	return stu;
}
Teacher searchTch(int account, char* password)
{
	Teacher tch = {};
	for(int i = 0; i < 100; i++)
	{
		if(account == teacher[i].id)
		{
			if(0 == strcmp(password, teacher[i].password))
			{
				strcpy(tch.name, teacher[i].name);
				strcpy(tch.password, teacher[i].password);
				tch.id = teacher[i].id;
				tch.sex = teacher[i].sex;
				tch.flag = teacher[i].flag;
				return tch;
			}
			else
			{
				tch.id = account;
				tch.flag = teacher[i].flag;
			}
			break;
		}
	}
	return tch;
}
void firstLogin(int identity, int id)
{
	printf("首次登陆需重置密码，请输入密码:\n");
	char newPassword[50];
	scanf("%s",newPassword);
	while(ifBeyond(newPassword,20))
	{
		printf("密码过长，请缩减至20位以内！\n");
		printf("请重新输入密码:\n");
		scanf("%s",newPassword);
	}
	if(1 == identity)
	{
		student[id-1001].flag = 1;
		strcpy(student[id-1001].password,newPassword);
	}
	else if(2 == identity)
	{
		teacher[id-101].flag = 1;
		strcpy(teacher[id-101].password,newPassword);
	}
	printf("重置成功，请重新登陆！\n");
	anykey_continue();
}

int ifBeyond(const char* str, int range)
{
	int len = strlen(str);
	if(len > range)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

char* inputPassword(void)
{
	char password[50] ={};
	char ch = 0;
	int cnt = 0;
	while(1)
	{
		ch = getch();
		if(ch == 10)
		{
			printf("\n");
			break;
		}
		if(ch == 127)
		{
			if(cnt > 0)
			password[--cnt] = 0;
			printf("\b");
			printf("%c",' ');
			printf("\b");
		}
		else
		{
			printf("*");
			password[cnt] = ch;
			cnt++;
		}
	}
	return password;
}
